﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Evan.Common
{
    public class Uploads
    {
        //private DtCms.Model.WebSet webset;
        private string filePath = Evan.Common.CommFun.GetAppSetting("Uploads"); //上传目录名
        private readonly string fileType = Evan.Common.CommFun.GetAppSetting("UploadType"); //文件类型
        private readonly long fileSize = int.Parse(Evan.Common.CommFun.GetAppSetting("UploadSize")) * 1024 * 1024; //文件大小0为不限制
        //private readonly int isWatermark = 0; //0为不加水印，1为文字水印，2为图片水印
        //private readonly int waterStatus = 9; //水印位置
        //private readonly int waterQuality = 100; //水印图片质量
        //private readonly string imgWaterPath = "/admin/webimages/water.png"; //水印图片地址
        //private readonly int waterTransparency = 50; //水印图片透时度
        //private readonly string textWater = "沙漠风"; //水印文字
        //private readonly string textWaterFont = "Tahoma"; //文字水印字体
        //private readonly int textFontSize = 18; //文字大小


        ///<summary>
        /// 文件上传方法
        /// </summary>
        public string fileSaveAs(HttpPostedFile _postedFile, string _path, int _isWater)
        {
            try
            {
                //Stream sm = _postedFile.InputStream.BeginRead()
                byte[] photoValue = new byte[2];
                _postedFile.InputStream.BeginRead(photoValue, 0, 2, null, "1");

                string _fileExt = _postedFile.FileName.Substring(_postedFile.FileName.LastIndexOf(".") + 1);
                //验证合法的文件
                if (!CheckFileExt(this.fileType, _fileExt))
                {
                    return "{\"result\": \"0\", \"msg\": \"不允许上传" + _fileExt + "类型的文件\"}";
                }
                if (_postedFile.ContentLength > fileSize)
                {
                    return "{\"result\": \"0\", \"msg\": \"文件超过限制的大小\"}";
                }
                string _fileName = ""; //随机文件名
                if (Regex.IsMatch(_postedFile.FileName.Replace(_fileExt, ""), "[\u4e00-\u9fa5]+"))
                {
                    _fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "." + _fileExt;
                }
                else
                {
                    _fileName = _postedFile.FileName;
                    if (_fileName.IndexOf("\\") > -1)
                    {
                        _fileName = _fileName.Substring(_fileName.LastIndexOf("\\") + 1);
                    }
                }
                string serverFileName = (string.IsNullOrEmpty(_path) ? this.filePath : this.filePath + _path + "/") + _fileName;
                if (File.Exists(HttpContext.Current.Server.MapPath(serverFileName)))
                {
                    _fileName = _fileName.Replace("." + _fileExt, "") + DateTime.Now.ToString("mmssff") + "." + _fileExt;
                    serverFileName = (string.IsNullOrEmpty(_path) ? this.filePath : this.filePath + _path + "/") + _fileName;
                }
                //检查保存的路径 是否有/开头结尾
                if (this.filePath.StartsWith("/") == false) this.filePath = "/" + this.filePath;
                if (this.filePath.EndsWith("/") == false) this.filePath = this.filePath + "/";

                //物理完整路径
                string toFileFullPath = HttpContext.Current.Server.MapPath((string.IsNullOrEmpty(_path) ? this.filePath : this.filePath + _path + "/"));
                //检查是否有该路径没有就创建
                if (!Directory.Exists(toFileFullPath))
                {
                    Directory.CreateDirectory(toFileFullPath);
                }
                //将要保存的完整文件名                
                string toFile = toFileFullPath + _fileName;
                //保存文件
                _postedFile.SaveAs(toFile);




                if (CheckFileExt("BMP|JPEG|JPG|GIF|PNG|TIFF", _fileExt))
                {
                    ////获得要保存的文件路径
                    //string minserverFileName = "/minimg" + (string.IsNullOrEmpty(_path) ? this.filePath : this.filePath + _path + "/") + _fileName;
                    ////物理完整路径                    
                    //string mintoFileFullPath = HttpContext.Current.Server.MapPath("/minimg" + (string.IsNullOrEmpty(_path) ? this.filePath : this.filePath + _path + "/"));
                    ////检查是否有该路径没有就创建
                    //if (!Directory.Exists(mintoFileFullPath))
                    //{
                    //    Directory.CreateDirectory(mintoFileFullPath);
                    //}

                    //////////ImageThumbnailMake.MakeThumbnail((string.IsNullOrEmpty(_path) ? this.filePath : this.filePath + _path + "/") + _fileName, minserverFileName, 140, 120);

                    //////////是否打图片水印
                    //////////if (isWatermark > 0 && _isWater == 1)
                    //////////{
                    //////////    switch (isWatermark)
                    //////////    {
                    //////////        case 1:
                    //////////            ImageWaterMark.AddImageSignText(this.filePath + _fileName, this.filePath + _fileName, this.textWater, waterStatus, waterQuality, textWaterFont, textFontSize);
                    //////////            break;
                    //////////        case 2:
                    //////////            ImageWaterMark.AddImageSignPic(this.filePath + _fileName, this.filePath + _fileName, this.imgWaterPath, waterStatus, waterQuality, waterTransparency);
                    //////////            break;
                    //////////    }
                    //////////}
                }
                return "{\"result\": \"1\", \"msg\": \"" + serverFileName + "\"}";
            }
            catch
            {
                return "{\"result\": \"0\", \"msg\": \"上传过程中发生意外错误！\"}";
            }
        }

        /// <summary>
        /// 检查是否为合法的上传文件
        /// </summary>
        /// <returns></returns>
        private bool CheckFileExt(string _fileType, string _fileExt)
        {
            string[] allowExt = _fileType.Split('|');
            for (int i = 0; i < allowExt.Length; i++)
            {
                if (allowExt[i].ToLower() == _fileExt.ToLower()) { return true; }
            }
            return false;
        }


        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="newPath"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        private void MakeThumbnail(string sourcePath, string newPath, int width, int height)
        {
            System.Drawing.Image ig = System.Drawing.Image.FromFile(sourcePath);
            int towidth = width;
            int toheight = height;
            int x = 0;
            int y = 0;
            int ow = ig.Width;
            int oh = ig.Height;
            if ((double)ig.Width / (double)ig.Height > (double)towidth / (double)toheight)
            {
                oh = ig.Height;
                ow = ig.Height * towidth / toheight;
                y = 0;
                x = (ig.Width - ow) / 2;

            }
            else
            {
                ow = ig.Width;
                oh = ig.Width * height / towidth;
                x = 0;
                y = (ig.Height - oh) / 2;
            }
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.Clear(System.Drawing.Color.Transparent);
            g.DrawImage(ig, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
            try
            {
                bitmap.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ig.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }

        }

    }
}
